package com.ljx.itbbs.server.user.service.impl;

import com.ljx.itbbs.common.exception.BusinessException;
import com.ljx.itbbs.server.user.dao.RolePermsRelationDao;
import com.ljx.itbbs.server.user.domain.entity.RolePermsRelationEntity;
import com.ljx.itbbs.server.user.domain.vo.req.RolePermsSaveReq;
import com.ljx.itbbs.server.user.service.RolePermsRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-04-02  19:25
 */
@Service
public class RolePermsRelationServiceImpl implements RolePermsRelationService {

    @Autowired
    private RolePermsRelationDao rolePermsRelationDao;

    @Override
    public void saveRolePerms(RolePermsSaveReq req) {
        try{
            // 删除该角色以及有的权限
            rolePermsRelationDao.deleteRolePermsByRoleId(req.getRoleId());
            // 添加传来的权限
            rolePermsRelationDao.saveBatch(getRolePermsList(req.getRoleId(), req.getPermsIds()));
        } catch (Exception e){
            throw new BusinessException("保存出错");
        }
    }

    private List<RolePermsRelationEntity> getRolePermsList(Long roleId, List<Long> permsIds) {
        return permsIds.stream().map(item -> {
            RolePermsRelationEntity rolePermsRelation = new RolePermsRelationEntity();
            rolePermsRelation.setPermsId(item);
            rolePermsRelation.setRoleId(roleId);
            return rolePermsRelation;
        }).collect(Collectors.toList());
    }
}
